package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public void addAddressBook(AddressBook addressBook) {

        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);

        addressBookMapper.addAddressBook(addressBook);

    }

    @Override
    public List<AddressBook> selectAddressBook() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        return addressBookMapper.getAddressBook(addressBook);
    }

    @Override
    public AddressBook selectDefaultAddressBook() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
        List<AddressBook> addressBook1 = addressBookMapper.getAddressBook(addressBook);

        return addressBook1.get(0);
    }

    @Override
    public void setDefaultAddressBook(AddressBook addressBook) {
        List<AddressBook> addressBooks = addressBookMapper.getAddressBook(AddressBook.builder().build());
        for (AddressBook book : addressBooks) {
            book.setIsDefault(0);
            addressBookMapper.updateAddressBook(book);
        }

        addressBook.setIsDefault(1);
        addressBookMapper.updateAddressBook(addressBook);

    }

    @Override
    public void updateAddressBook(AddressBook addressBook) {

        addressBookMapper.updateAddressBook(addressBook);

    }

    @Override
    public AddressBook selectAddressBookById(Long id) {

        return addressBookMapper.selectAddressBookById(id);

    }

    @Override
    public void deleteAddressBookById(Long id) {

        addressBookMapper.deleteAddressBookById(id);

    }


}
